#include<stdio.h>
//#include<stdlib.h>
#include <unistd.h>
#include<pthread.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;
int count=5;
bool waitflag = false;

void *decrement(void *arg)
{
	while(1)
	{
	    pthread_mutex_lock(&mutex);
        while(!waitflag)
        {
	        pthread_cond_wait(&cond,&mutex);
        }
	    printf("decre is %d\n",count);
	    waitflag = false;
	    pthread_mutex_unlock(&mutex);    
        pthread_cond_signal(&cond);

	}
}

void *increment(void *arg)
{
	while(1)
	{
		//sleep(1);
        int ret = 0;
	    count=count+1;
	    pthread_cond_signal(&cond);
        
        pthread_mutex_lock(&mutex);
        while(waitflag)
        {
	        pthread_cond_wait(&cond,&mutex);
        }
	    printf("count=%d,change cond state!\n",count);
	    waitflag = true;
	    pthread_mutex_unlock(&mutex);

	}
}

int main()
{
    int i1=1,i2=1;
    pthread_t id1,id2;
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    pthread_cond_init(&cond1,NULL);
    pthread_create(&id1,NULL,decrement,NULL);
    pthread_create(&id2,NULL,increment,NULL);
    
    i2=pthread_join(id2,NULL);
    i1=pthread_join(id1,NULL);
    if((i2==0)&&(i1==0))
    {
        printf("count=%d,the main thread!\n",count);
        pthread_cond_destroy(&cond);
        pthread_mutex_destroy(&mutex);
        return 0;
    }
}
